﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyERP.Models;

namespace MyERP.WebApi
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    [Authorize(Roles = "admin,q3")]
    public class ClientController : ControllerBase
    {
        private readonly MyDbContext db;
        public ClientController(MyDbContext myDbContext)
        {
            db = myDbContext;
        }
        /// <summary>
        /// 返回客户名称
        /// </summary>
        [HttpGet]
        public List<string> AllName()
        {
            return db.Client.Select(x => x.Name).ToList();
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="sData"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add([FromBody] Client cData)
        {
            //判断客户是否存在，如果不存在再继续添加客户
            Client? s = db.Client.FirstOrDefault(a => a.Name == cData.Name);
            if (s == null)
            {
                db.Client.Add(cData);
                await db.SaveChangesAsync();
                return Ok();
            }
            return NotFound();
        }
    }
}
